package com.feifei.controller;

import com.feifei.service.FileService;
import com.feifei.service.UserService;
import com.feifei.vo.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @Author: lee
 * @Date: 2022/4/25 11:18
 */
@CrossOrigin
@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired
    FileService fileService;

    /**
     * 上传文件
     * @param path 文件的相对路径
     * @param file 文件数据
     * @param request 请求
     * @return 文件的绝对路径
     */
    @ResponseBody
    @RequestMapping("/upload")
    public Result fileUpload(String path, @RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        // 先获取到文件要保存的路径

       // String realPath = request.getSession().getServletContext().getRealPath("/" + path);
        String realPath = "D:\\Java\\workspace\\rowdfunding_system\\src\\main\\resources\\pics";
        System.out.println("【绝对路径】" + realPath);
        // 获取文件后缀名，然后为文件起一个新名字（使用 UUID 避免重名）
        System.out.println("【原文件名】" + file.getOriginalFilename());
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + suffix;
        System.out.println("【新文件名】" + newFileName);
        // 新建一个文件对象
        File target = new File(realPath, newFileName);

        // 如果存放路径不存在，就新建一个
        if (!target.getParentFile().exists()) {
            // 新建文件夹
            if (!target.getParentFile().mkdirs()) {
                System.out.println("【目录为空】新建文件夹失败！");
                return null;
            }
        }


        // 成功的话将文件保存
        file.transferTo(target);
        //传给oss方法
        String filePath=realPath+"\\"+newFileName;
        String url = fileService.aliOSSUpload(newFileName, filePath);
//        String str="file:///"+realPath+"\\"+newFileName;
        Result result=new Result();
        result.setMsg("上传成功");
        result.setStatus(true);
        result.setData(url);
        return result;
    }


    @GetMapping("download/{fileName:.+}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable("fileName") String fileName, @RequestHeader("User-Agent") String userAgent, HttpServletRequest request) throws IOException {
       // String realPath = request.getSession().getServletContext().getRealPath("/" + "null");
        String realPath = "D:\\Java\\workspace\\rowdfunding_system\\src\\main\\resources\\pics";

        File downloadFile = new File(realPath, fileName);
        byte[] data = FileUtils.readFileToByteArray(downloadFile);
        //解决ie下载时文件名乱码的问题
        userAgent = userAgent.toUpperCase();
        //判断是否是ie浏览器
        if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT") || userAgent.contains("EDGE")) {
            //IE下载文件名乱码可以直接通过URL编码解决
            fileName = URLEncoder.encode(fileName, "UTF-8"); //StandardCharsets.UTF_8.name();
        }else{
            //其他浏览器需要使用转码进行解决
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
        headers.add("Content-Disposition", "attachment; filename=" + fileName);
        return new ResponseEntity<>(data, headers, HttpStatus.OK);
    }


}
